package com.zf.spring.microservice.service.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ChannelUtil {
	private static final Logger logger = LoggerFactory
			.getLogger(ChannelUtil.class);

	public static void writeResponseMessage(ResponseMessage responseMessage, ChannelHandlerContext ctx,
			HttpRequest request) {
		FullHttpResponse response = new DefaultFullHttpResponse(
				HttpVersion.HTTP_1_1,
				HttpResponseStatus.OK,
				Unpooled.copiedBuffer(responseMessage.toString(), CharsetUtil.UTF_8));
		response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");

		boolean keepAlive = request == null ? false : HttpUtil.isKeepAlive(request);

		if (keepAlive) {
			response.headers().setInt(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
			response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}

		ctx.write(response);

		if (!keepAlive) {
			// If keep-alive is off, close the connection once the content is
			// fully written.
			ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
		}
	}

	/**
	 * 获取客户端IP。
	 */
	public static String[] getIpAddress(ChannelHandlerContext ctx, HttpRequest request) {
		String ips[] = null;
		try {
			HttpHeaders httpHeaders = request.headers();
			for (Entry<String, String> entry : httpHeaders) {
				if ("x-forwarded-for".equalsIgnoreCase(entry.getKey())) {
					ips = entry.getValue().split(",");
				} else if ("X-Real-IP".equalsIgnoreCase(entry.getKey())) {
					ips = new String[] { entry.getValue() };
				}
			}
			if (ips == null) {
				InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
				ips = new String[] { remoteAddress.getAddress().getHostAddress() };
			}
		} catch (Exception e) {
			logger.warn("获取IP失败", e);
		}
		return ips;
	}
}
